package org.laobai.permission.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.laobai.permission.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {

    @Value("${jwt.secret}")
    private String secret = "xxxxxxx";

    @Value("${jwt.expirationTime}")
    private String expirationTime="60";

    // 外部http请求中 header中 token的 键值
    private String header = "token";

    private static Map<String, String> tokenMap = new HashMap<>();

    /**
     * 生成token
     *
     * @param subject
     * @return
     */
    public String createToken(String subject) {
        Date nowDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
        calendar.add(Calendar.MINUTE, Integer.valueOf(expirationTime));
        Date expireDate = calendar.getTime();

        String userToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(subject)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
        // 把token添加到缓存中
        tokenMap.put(subject, userToken);
        return userToken;
    }

    public String createRefreshToken(String subject) {
        Date nowDate = new Date();
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(subject)
                .setIssuedAt(nowDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 获取token中注册信息
     *
     * @param token
     * @return
     */
    public Claims getTokenClaim(String token) {
        if (token == null) {
            return null;
        }
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            //登陆过期，或token错误
            return null;
        }
    }

    /**
     * 验证token是否过期失效
     *
     * @param token
     * @return
     */
    public boolean isTokenExpired(String token) {
        Date expiration = getTokenClaim(token).getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 验证token是否过期失效
     *
     * @param expirationTime
     * @return
     */
    public boolean isTokenExpired(Date expirationTime) {
        return expirationTime.before(new Date());
    }

    /**
     * 获取token失效时间
     *
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token) {
        return getTokenClaim(token).getExpiration();
    }

    /**
     * 获取用户名从token中
     */
    public String getUsernameFromToken(String token) {
        return getUserFromToken(token).getUsername();
    }

    public Integer getUserIdFromToken(String token) {
        return getUserFromToken(token).getId();
    }

    public User getUserFromToken(String token) {
        Claims tokenClaim = getTokenClaim(token);
        if (tokenClaim == null) {
            return null;
        }
        String userJson = tokenClaim.getSubject();

        return JsonUtils.jsonToPojo(userJson,User.class);
    }


    /**
     * 获取jwt发布时间
     */
    public Date getIssuedAtDateFromToken(String token) {
        return getTokenClaim(token).getIssuedAt();
    }

    public static void main(String[] args) {
        JwtUtils jwtUtils = new JwtUtils();

        User user = new User();
        user.setId(1);
        user.setName("张是哪");

        String token = jwtUtils.createToken(JsonUtils.objectToJson(user));

        User userFromToken = jwtUtils.getUserFromToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ7XCJpZFwiOm51bGwsXCJuYW1lXCI6bnVsbCxcImhlYWRJbWdcIjpudWxsLFwic2V4XCI6bnVsbCxcInBob25lXCI6bnVsbCxcInRlbGVwaG9uZVwiOm51bGwsXCJhZGRyZXNzXCI6bnVsbCxcImVuYWJsZWRcIjpudWxsLFwidXNlcm5hbWVcIjpcImFkbWluXCIsXCJwYXNzd29yZFwiOlwiYWRtaW5cIixcInJlbWFya1wiOm51bGwsXCJwcm92aW5jZVwiOm51bGwsXCJjaXR5XCI6bnVsbCxcImRpc3RyaWN0XCI6bnVsbCxcInVzZXJmYWNlXCI6bnVsbCxcImxvY2F0aW9uXCI6bnVsbCxcInJpZHNcIjpudWxsfSIsImlhdCI6MTYzNzcyMjY2OSwiZXhwIjoxNjM3NzI2MjY5fQ.FgnNx0og9soQ-b5IguCAX4sbYuYl27BFWQuaCwhJ2HfqQ2PMyBx0NewcBqByPlDl2oLTb_EzkYKAY3RSlcQirw");
        System.out.println(userFromToken.getId());
        System.out.println(userFromToken.getName());
    }

}
